<?php

class openapi_api_function_v1_advance extends openapi_api_function_abstract implements openapi_api_function_interface{

    
	public function getlogs($params,&$code,&$sub_msg)
	{
		$member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
		$nPage = empty($params['npage'])?1:$params['npage'];
		$pagesize = empty($params['pagesize'])?10:$params['pagesize'];
        $member = app::get('b2c')->model('members');
        $mem_adv = app::get('b2c')->model('member_advance');
        $items_adv = $mem_adv->get_list_bymemId($member_id);
        $count = count($items_adv);
        $aPage = $this->get_start($nPage,$pagesize,$count);
        $page['data'] = $mem_adv->getList('*',array('member_id' => $member_id),$aPage['start'],$pagesize,'mtime desc');
        $page['page'] = $aPage['maxPage'];
        $result['pager'] = $this->pagination($nPage,$page['page'],'advance', '', 'business', 'site_member');
        $result['advlogs'] = $page['data'];
        if(!$result['advlogs']){
			return $this->apiData(false,null,400,app::get('b2c')->_('暂无记录'));
        }
        $data = $member->dump(app::get('b2c')->member_id,'advance');
        return $this->apiData(true,$result,200);
	}

    
    public function applycrash($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $currMember = app::get('b2c')->model('members')->getRow("advance",array('member_id'=>$member_id));
        $type = app::get('b2c')->getConf('advance.withdraw.type');
        $fee = floatval(app::get('b2c')->getConf('advance.withdraw.fee'));
        $app_ectools = app::get('ectools');
        if($type == '1'){
            $app_ectools = app::get('ectools');
            $decimals = app::get('b2c')->getConf('system.money.decimals');
            $operation_carryset = app::get('b2c')->getConf('system.money.operation.carryset');
            $fee = $app_ectools->model('currency')->changer_odr($fee,null,false,false,$decimals,$operation_carryset);
        }else{
            $fee = number_format($fee*100, 2).'%';
        }
        $storeInfo = app::get('business')->model('storemanger')->dump(array('account_id'=>$member_id));
        $bank['bank_name'] = $storeInfo['bank_name'];
        $bank['bank_cardid'] = $storeInfo['bank_cardid'];
        $bank['bank_cardname'] = $storeInfo['store_idcardname'];
        $result['type'] = $type;
        $result['fee'] = $fee;
        $result['bank'] = $bank;
        $result['advance'] = $currMember['advance'];
        return $this->apiData(true,$result,200);
    }

    
    function withdraw($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $type = app::get('b2c')->getConf('advance.withdraw.type');
        $fee = floatval(app::get('b2c')->getConf('advance.withdraw.fee'));
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();
        $objAdvance = app::get('b2c')->model("member_advance");
        $money = abs($params['money']);
        $memo = $params['memo'];
        $is_frontend = true;
        if($type != '1') $fee = $money * $fee;
        $status = $objAdvance->deduct($member_id, ($money+$fee), app::get('business')->_('提现申请'), $errorMsg, '', '', '', $memo,$is_frontend);
        if ($status){
            $data = $bank;
            $data['member_id'] = $member_id;
            $data['money'] = $money;
            $data['memo'] = $memo;
            $data['bank_name'] = $params['bank_name'];
            $data['bank_cardname'] = $params['bank_cardname'];
            $data['bank_cardid'] = $params['bank_cardid'];
            $data['mtime'] = time();
            $data['fee'] = $fee;
            if(app::get('b2c')->model('member_advance_getout')->save($data)){
                $db->commit($transaction_status);
                $currMember = app::get('b2c')->model('members')->getRow("advance",array('member_id'=>$member_id));
                return $this->apiData(true,array('current_advance'=>$currMember['advance']),200,app::get('b2c')->_('提现申请成功！'));
            } 
        }
        $db->rollback();
        $currMember = app::get('b2c')->model('members')->getRow("advance",array('member_id'=>$member_id));
        return $this->apiData(false,array('current_advance'=>$currMember['advance']),400,app::get('b2c')->_('操作失败'));
    }

    
    public function transfer($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $currMember = app::get('b2c')->model('members')->getRow("advance,advance_freeze",array('member_id'=>$member_id));
        return $this->apiData(true,$currMember,200);
    }

    
    public function dotransfer($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $currMember = app::get('b2c')->model('members')->getRow("*",array('member_id'=>$member_id));
        $uname = trim($params['to_uname']);
        $params['to_uname'] = $uname;
        $params['member_id'] = $member_id;
        if(empty($uname)){
            return $this->apiData(false,null,400,app::get('business')->_('用户名不能为空！'));
        }
        $obj_members = app::get('b2c')->model('members');
        $flag = $obj_members->is_exists($uname);
        if(!$flag){
            return $this->apiData(false,null,400,app::get('business')->_('用户名不存在！'));
        }
        $advance = $currMember['advance'] - $currMember['advance_freeze'];
    
        if($advance < $params['money']){
            return $this->apiData(false,null,400,app::get('b2c')->_('账户可用余额不足！'));
        }

        $obj_members = app::get('b2c')->model('members');
        $minfo = $obj_members->getMemberByUname($uname);
        $result = $params;
        $result['mobile'] = $minfo['mobile'];
        $result['email'] = $minfo['email'];
        $result['advance'] = $advance;
        return $this->apiData(true,$result,200,app::get('b2c')->_('请确认信息'));
    }

    
    public function transfer_pay($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $currMember = app::get('b2c')->model('members')->getRow("*",array('member_id'=>$member_id));
        $login_name = app::get('pam')->model('account')->getRow("*",array('account_id'=>$member_id));
        $currMember['uname'] = $login_name['login_name'];
        $pwd = $params['pay_password'];
        if(!$currMember['pay_password']){
            return $this->apiData(false,null,400,app::get('b2c')->_('您还没有设置支付密码！'));
        }elseif(md5($pwd)!=$currMember['pay_password']){
            return $this->apiData(false,null,400,app::get('b2c')->_('您输入的支付密码不正确，请重新输入！'));
        }
        //支付密码正确，转账
        $pay_password = $params['pay_password'];         
        $mdl_transfer = app::get('b2c')->model('member_transfer');
        $mdl_members = app::get('b2c')->model('members');
        $transfer = $params;
        $transfer['create_time'] = time();
        $minfo = $mdl_members->getMemberByUname($transfer['to_uname']);   
        if($mdl_transfer->save($transfer)){
            $data1 = array(
                        'modify_advance' => -$transfer['money'],
                        'modify_memo' => '',
                        'message' => "向{$transfer['to_uname']}转账扣款（转账记录ID：{$transfer['id']}）"
                );
            if(!app::get('b2c')-> model('member_advance') -> adj_amount($transfer['member_id'], $data1, $msg, false)) {
                return $this->apiData(false,$params,400,$msg);
            }
            $data2 = array(
                        'modify_advance' => $transfer['money'],
                        'modify_memo' => '',
                        'message' => "{$currMember['uname']}转账增值（转账记录ID：{$transfer['id']}）"
                );
            if(!app::get('b2c')->model('member_advance')->adj_amount($minfo['member_id'], $data2, $msg, false)) {
                return $this->apiData(false,$params,400,$msg);
            }
            //发送站内信
            $data3['to_id'] = $minfo['member_id'];
            $data3['msg_to'] = $transfer['to_uname'];
            $data3['subject'] = app::get('b2c')->_("{$currMember['uname']}向你转账");
            $tmp_msg = empty($transfer['message'])?"":",留言：{$transfer['message']}";
            $data3['comment'] = app::get('b2c')->_("转账金额{$transfer['money']}".$tmp_msg);
            $data3['has_sent'] = 'true';
            $data3['deal_type'] = '1';
            $data3['member_id'] = $member_id;
            $data3['uname'] = $currMember['uname'];
            kernel::single('b2c_message_msg')->send($data3);
            return $this->apiData(true,null,200,app::get('business')->_('转账成功！'));
        }else{
            return $this->apiData(false,$params,400,app::get('business')->_('转账失败！'));
        }
    }

    
    public function total_advance($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(!$member_id){
            return $this->apiData(false,null,301,app::get()->_('请登录'));
        }
        $storeid = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        if(empty($storeid)){
            return $this->apiData(false,null,400,app::get('b2c')->_('获取数据失败'));
        }
        $db = kernel::database();
        //我的提现
        $sql = "select sum(money) total from " . DB_PREFIX . "b2c_member_advance_getout where member_id='".$member_id."' and approved='1' and sendmoney='1'";
        $getout = $db->select($sql);
        $getout = $getout[0]['total'];

        //我的进货总消费额
        $my_sql = "select sum(final_amount) total from " . DB_PREFIX . "b2c_orders where pay_status='1' and status='finish' and member_id='".$member_id."'";
        $my_purchase_advance = $db->select($my_sql);
        //我的下级进货总消费额
        $sub_sql = "select sum(final_amount) total from " . DB_PREFIX . "b2c_orders where pay_status='1' and status='finish' and store_id in ('".$storeid['store_id']."')";
        $sub_purchase_advance = $db->select($sub_sql);
        $income = $sub_purchase_advance[0]['total'] - $my_purchase_advance[0]['total'];
        //站内币金额
        $advance = app::get('b2c')->model('members')->dump($member_id,'advance');
        //授信额度
        $oncredit = app::get('business')->model('storemanger_oncredit')->getMyCredit($member_id);
        $result = array(
            'getout'=>$getout,
            'income'=>$income,
            'total'=>$advance['advance']['total'],
            'oncredit'=>$oncredit
        );
        return $this->apiData(true,$result,200);
    }

}